//** React
import { FC, useEffect, useState } from "react";
import { useAPI } from "../../hooks/useAPI.ts";
import dayjs from "dayjs";

//** Arco
import {
  Button,
  DatePicker,
  Form,
  Input,
  Message,
  Tag,
  Tooltip,
} from "@arco-design/web-react";
import { IconRefresh } from "@arco-design/web-react/icon";

//** MUI
import Box from "@mui/material/Box";
import { alpha, styled } from "@mui/material/styles";
import { DataGrid, gridClasses, zhCN } from "@mui/x-data-grid";

//** Custom
import { ViewVideoRecordModal } from "../ViewVideoRecordModal";
import { loadServerRows } from "./RiskHandleRecord.tsx";
import { Icon } from "@iconify/react";

export const formatDuration = (seconds: number) => {
  if (isNaN(seconds) || seconds < 0) return "Invalid duration";

  const secondsInMinute = 60;
  const secondsInHour = 3600;
  const secondsInDay = 86400; // 24 * 60 * 60
  const secondsInMonth = 2592000; // Average number of seconds in a month (30 days)
  const secondsInYear = 31536000; // Average number of seconds in a year (365 days)

  const years = Math.floor(seconds / secondsInYear);
  const months = Math.floor((seconds % secondsInYear) / secondsInMonth);
  const days = Math.floor((seconds % secondsInMonth) / secondsInDay);
  const hours = Math.floor((seconds % secondsInDay) / secondsInHour);
  const minutes = Math.floor((seconds % secondsInHour) / secondsInMinute);
  const secs = Math.floor(seconds % secondsInMinute);

  const parts = [];
  if (years > 0) parts.push(`${years}年`);
  if (months > 0) parts.push(`${months}月`);
  if (days > 0) parts.push(`${days}日`);
  if (hours > 0) parts.push(`${hours}时`);
  if (minutes > 0) parts.push(`${minutes}分`);
  if (secs > 0) parts.push(`${secs}秒`);

  return parts.join(" ");
};

export const calculateDuration = (start: number, end: number) => {
  const startDate: number = new Date(start * 1000).getTime();
  const endDate: number = new Date(end * 1000).getTime();
  const duration: number = endDate - startDate;
  return formatDuration(Math.round(duration / 1000.0));
};

export const findRisk = (status: any) => {
  switch (status) {
    case "warning":
      return <Tag color="orange">中风险</Tag>;
    case "danger":
      return <Tag color="red">高风险</Tag>;
    default:
      return <Tag color="green">正常</Tag>;
  }
};

export const timestampToLocalTime = (timestamp: number) => {
  const date = new Date(timestamp);

  // Manually constructing the date string
  const y = date.getFullYear();
  const m = `0${date.getMonth() + 1}`.slice(-2); // getMonth is zero-based, add 1
  const d = `0${date.getDate()}`.slice(-2);
  const hours = `0${date.getHours()}`.slice(-2);
  const minutes = `0${date.getMinutes()}`.slice(-2);
  const seconds = `0${date.getSeconds()}`.slice(-2);

  return `${y}-${m}-${d} ${hours}:${minutes}:${seconds}`;
};

const ODD_OPACITY = 0.1;

// @ts-ignore
export const StripedDataGrid = styled(DataGrid)(({ theme }) => ({
  [`& .${gridClasses.row}.even`]: {
    backgroundColor: theme.palette.grey[200],
    "&:hover": {
      backgroundColor: alpha(theme.palette.primary.main, ODD_OPACITY),
      "@media (hover: none)": {
        backgroundColor: "transparent",
      },
    },
    "&.Mui-selected": {
      backgroundColor: alpha(
        theme.palette.primary.main,
        ODD_OPACITY + theme.palette.action.selectedOpacity,
      ),
      "&:hover": {
        backgroundColor: alpha(
          theme.palette.primary.main,
          ODD_OPACITY +
          theme.palette.action.selectedOpacity +
          theme.palette.action.hoverOpacity,
        ),
        // Reset on touch devices, it doesn't add specificity
        "@media (hover: none)": {
          backgroundColor: alpha(
            theme.palette.primary.main,
            ODD_OPACITY + theme.palette.action.selectedOpacity,
          ),
        },
      },
    },
  },
}));

// @ts-ignore
export const ActivityListAndRecord: FC<{
  userId: number | string;
  dateRange: string;
  setDateRange(dateRange: string[]): void;
}> = ({ userId, dateRange, setDateRange }) => {
  const api = useAPI();
  const [formRef] = Form.useForm<any>();
  const [data, setData] = useState({ data: [], recordsTotal: 0 });
  const [paginationModel, setPaginationModel] = useState({
    pageSize: 11,
    page: 0,
  });

  const [loading, setLoading] = useState(true); // Loading state
  const [suid, setSuid] = useState("");
  const [report, setReport] = useState("null");
  const [id, setId] = useState<number>(-1);
  const [isOpenViewVideoRecordModal, setIsViewVideoRecordModal] =
    useState(false);
  const [time, setTime] = useState("");
  const [refresh, setRefresh] = useState(false);
  const [search, setSearchValues] = useState("");
  const [action, setAction] = useState(null);

  useEffect(() => {
    setLoading(true);
    loadServerRows(
      paginationModel,
      [dateRange, dateRange],
      userId,
      api,
      4,
      search,
    ).then((response) => {
      response.data.data = response.data?.data.map(
        (row: any, index: number) => ({
          index: index + 1 + paginationModel.page * paginationModel.pageSize, // Add index starting from 1
          ...row,
        }),
      );
      setData(response.data);
      setLoading(false);
    });
  }, [paginationModel, dateRange, refresh, search]);

  const deleteRecord = (id: number) => {
    api
      .deleteRiskProcessingLog({
        id,
        userId,
        suid,
        data: {
          pics: "", files: "",
          method: 0,
          report: {
            userId: window.localStorage.getItem("loggedUserId"),
            nickName: window.localStorage.getItem("loggedNickName"),
          },
          time: dayjs().format("YYYY-MM-DD HH:MM:s"),
        },
      })
      .then((r) => {
        if (r.data.code == "3001") {
          Message.info("操作成功");
          setRefresh(!refresh);
        }
      });
  };

  return data ? (
    <div>
      <ViewVideoRecordModal
        videoList={suid}
        id={id}
        userId={userId}
        report={report}
        visible={isOpenViewVideoRecordModal}
        eventTime={time}
        onClose={() => setIsViewVideoRecordModal(false)}
        refresh={() => setRefresh(!refresh)}
        deleteRecord={deleteRecord}
        action={action}
      />

      <Form form={formRef} layout="inline">
        <Form.Item label="查询日期：">
          <DatePicker
            onChange={(e) => {
              setDateRange([e, e]);
            }}
            defaultValue={dateRange}
            disabledDate={(current) => current.isAfter(dayjs())}
          />
        </Form.Item>
        <Form.Item label="搜索：">
          <Input.Search
            value={search}
            onChange={(value) => {
              setSearchValues(value);
            }}
            placeholder="请输入关键字"
            style={{ width: "200px" }}
            allowClear
          />
        </Form.Item>
        <Form.Item>
          <Button
            type="outline"
            onClick={() => {
              formRef.resetFields();
            }}
          >
            <IconRefresh />
            重置
          </Button>
        </Form.Item>
      </Form>

      <Box
        sx={{
          height: 500,
          width: "100%",
          textAlign: "center",
        }}
      >
        <StripedDataGrid
          density="compact"
          rows={data.data}
          rowCount={data.recordsTotal}
          loading={loading}
          getRowClassName={(params) =>
            params.indexRelativeToCurrentPage % 2 === 0 ? "even" : "odd"
          }
          columns={[
            {
              field: "index",
              headerName: "序号",
              minWidth: 5,
              align: "center", // Center the cell content
              headerAlign: "center", // Center the header content
            },
            {
              field: "startTime",
              headerName: "开始时间",
              minWidth: 180,
              valueGetter: (value: any) =>
                timestampToLocalTime(value.row.startTime * 1000.0),
              align: "center", // Center the cell content
              headerAlign: "center", // Center the header content
            },
            {
              field: "endTime",
              headerName: "持续时间",
              valueGetter: (value: any) =>
                calculateDuration(value.row.startTime, value.row.endTime),
              align: "center", // Center the cell content
              headerAlign: "center", // Center the header content
              minWidth: 180,
            },
            {
              field: "actCn",
              headerName: "活动名称",
              align: "center", // Center the cell content
              headerAlign: "center", // Center the header content
              minWidth: 180,
            },
            {
              field: "riskLevel",
              headerName: "风险等级",
              renderCell: (value: any) => findRisk(value.row.riskLevel),
              align: "center", // Center the cell content
              headerAlign: "center", // Center the header content
            },
            {
              field: "cmd",
              headerName: "操作",
              align: "center", // Center the cell content
              headerAlign: "center", // Center the header content
              renderCell: (value: any) => {
                const suid = JSON.parse(value.row.suid);
                return suid.length > 0 ? (
                  <Tooltip content="查看回放">
                    <Button
                      size="small"
                      shape="round"
                      type="outline"
                      icon={<Icon icon="tabler:repeat" />}
                      onClick={(e) => {
                        e.preventDefault();
                        e.stopPropagation();
                        setIsViewVideoRecordModal(true);
                        setSuid(suid.length > 0 ? suid[0] : "");
                        setReport(value.row.report);
                        setId(value.row.id);
                        setAction(value.row.actCn);
                        setTime(
                          timestampToLocalTime(value.row.startTime * 1000.0),
                        );
                      }}
                    />
                  </Tooltip>
                ) : (
                  <div></div>
                );
              },
            },
          ]}
          paginationMode="server"
          paginationModel={paginationModel}
          onPaginationModelChange={setPaginationModel}
          pageSizeOptions={[10]}
          disableRowSelectionOnClick
          localeText={zhCN.components.MuiDataGrid.defaultProps.localeText}
        />
      </Box>
    </div>
  ) : null;
};
